#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#include "misc.h"
#include "func.h"

void TimerInit(void)
{
    TIM_TimeBaseInitTypeDef timeInitStruct;
    NVIC_InitTypeDef nvicInitStruct;

    // TCLK = 2 * PCLK1 = HCLK / 2 = 84M
    // 1s = (period + 1) * (psc + 1) / TCLK
    RCC_APB1PeriphClockCmd(RCC_APB1ENR_TIM3EN, ENABLE);
    timeInitStruct.TIM_Period = 9999;
    timeInitStruct.TIM_Prescaler = 8199;
    timeInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    timeInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &timeInitStruct);

    nvicInitStruct.NVIC_IRQChannel = TIM3_IRQn;
    nvicInitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    nvicInitStruct.NVIC_IRQChannelSubPriority = 2;
    nvicInitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&nvicInitStruct);

    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM3, ENABLE);
}

void TIM3_IRQHandler(void)
{
    LED1 = !LED1;
    LED2 = !LED2;
    LED3 = !LED3;
    LED4 = !LED4;
    TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
